<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use App\Models\SeniorTeamLeader;
use App\Models\User;
use App\Models\GoldCoin;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Collection;

class GrantTeamSupport extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cc:grant-team-support';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $seniorTeamCount = cs("storm")->senior_team_number;

        $startDate = Carbon::now()->subDays(7);
        $endDate = Carbon::now();

        SeniorTeamLeader::query()->chunk(50, function (Collection $leaders) use($seniorTeamCount,$startDate,$endDate) {

            if ($leaders->isEmpty()) return false;

            /**
             * @var User $user
             */
            foreach ($leaders as $leader) {

               $childrenCount = User::query()->where("parent_id",$leader->user_id)->where("is_gold_intern",true)->count();
               if($childrenCount >= $seniorTeamCount){
                    $teamPrize =  GoldCoin::query()->where("user_id",$leader->user_id)->where("remark","gold_record_team_prize")->whereBetween('created_at', [$startDate, $endDate])->sum("money");

                    account_coins($leader->user)->plusSupportTeamCoins($teamPrize);

               }
            }

            return true;

        });
    }
}
